# -*- coding: utf-8 -*-
# @Time    : 2020/1/25 0025 23:32
# @Author  : 撸小鱼
# @Email   : lofish@foxmail.com

import requests
import MySQLdb as mdb

from MySQLdb import escape_string

con = None

header = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3741.400 QQBrowser/10.5.3863.400'
}

track_map = {}


# 获取专辑列表
# album_id 专辑ID
# page_num 页码
def get_track_list(album_id, page_num):
    url = "https://www.ximalaya.com/revision/album/v1/getTracksList?albumId=" + str(album_id) + "&pageNum=" + str(
        page_num)
    
    track_list = []
    resp = requests.get(url, headers=header)
    result = resp.json()
    if result['ret'] == 200:
        tracks = result['data']['tracks']
        for tack in tracks:
            track_list.append(
                {'index': tack['index'], 'play_count': tack['playCount'], 'duration': tack['duration'], 'trackId': tack['trackId'], 'title': tack['title'],
                 'url': tack['url']})
            # 加入字典
            track_map[tack['trackId']] = tack['title']
    return track_list


# 获取音频地址
def get_track_url(track_id):
    url = "https://www.ximalaya.com/revision/play/v1/audio?id=" + str(track_id) + "&ptype=1"
    resp = requests.get(url, headers=header)
    result = resp.json()
    if result['ret'] == 200:
        track_audio_play = result['data']['src']
        if len(track_audio_play) > 0:
            return track_audio_play

# 下载音频文件
def download_track_audio(url, file):
    resp = requests.get(url, headers=header, stream=True)
    with open(file, "wb") as f:
        for data in resp.iter_content(chunk_size=1024):
            if data:
                f.write(data)


try:
    dir = "H:/Temp"
    # 连接 mysql 的方法：connect('ip','user','password','dbname')
    con = mdb.connect(host='127.0.0.1', user='root', passwd='123456', db='py_demo', use_unicode=True, charset="utf8")
    # 所有的查询，都在连接 con 的一个模块 cursor 上面运行的
    cur = con.cursor()
    # 执行一个查询
    # cur.execute("SELECT VERSION()")
    # 取得上个查询的结果，是单个结果
    # data = cur.fetchone()
    track_list = get_track_list(18521227, 1)
    sql = """insert into track_info_demo(id,trackId,title,play_count,duration,url,file_path) values(%s,%s,%s,%s,%s,%s,%s)"""
    for track_info in track_list:
        
        # 下载
        track_url = get_track_url(track_info.get('trackId'))
        file_path = ""
        if track_url:
            # 扩展名
            file_name = track_url[track_url.rindex('/'):]
            # 文件名路径
            file_path = dir + file_name
            # 下载
            download_track_audio(track_url, file_path)
        
        # values.append(track_info.get('index'))
        # values.append(track_info.get('trackId'))
        values = [track_info.get('index'), track_info.get('trackId'), track_info.get('title'), track_info.get('playCount'), track_info.get('duration'),
                  track_info.get('url'), file_path]
        cur.execute(sql, values)
    
    con.commit()
finally:
    if con:
        # 无论如何，连接记得关闭
        con.close()
